package org.third.integration.http;



import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class IdmTest {

    private String xAuthToken = "";
    private String idmService = "https://gongyo2.asiapacific.hpqcorp.net:8443/idm-service";
private static final Logger logger  =LoggerFactory.getLogger(IdmTest.class);
    public static final String getAccessToken = "/idm/v0/api/token/access_token";
    public static final String getRequestToken = "/idm/v0/api/token/request_token";
    public static final String authenticate = "/idm/v0/api/token/access_token";

    private static final String integratedUser = "idmTransportUser";
    private static final String integratedPwd = "idmTransportUser";
    org.apache.http.impl.client.CloseableHttpClient httpclient = null;

    @Before
    public void setup() {
        httpclient = org.apache.http.impl.client.HttpClients.createDefault();
    }

    public static final SSLSocketFactory getSslSocketFactory() throws Exception {
        SSLSocketFactory factory = null;
        FileInputStream trustStoreStream = null;
        String trustStore="C:/Users/gongyo/workspace/idm/idm_client_view1/idm-sdk-web/idm-client-core/src/test/resources/trustStore.keystore", trustStorePassword="tomcat1";
        try {
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

            File f = new File(trustStore);
            if (!f.exists()) {
                throw new FileNotFoundException("Trust Store File - " + f + " Not Found");
            }
            trustStoreStream = new FileInputStream(f);

            keyStore.load(trustStoreStream, trustStorePassword.toCharArray());

            TrustManagerFactory trustMgrFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustMgrFactory.init(keyStore);
            TrustManager []tms = new TrustManager[1];
//            tms=trustMgrFactory.getTrustManagers();
            tms[0] = new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    
                }

                @Override
                public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    
                }
            };

            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            sslContext.init(null, tms, null);

            factory = sslContext.getSocketFactory();
            return factory;

        } catch (Exception e) {
            logger.debug("csaTruststore:" + trustStore);
            logger.error("Error Creating SSLSocketFactory", e);
            throw e;
        } finally {
            if (trustStoreStream != null) {
                trustStoreStream.close();
            }
        }
    }

    @Test
    public void getRequestToken() throws Exception {
        URL url = new URL(idmService + getRequestToken);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        if (connection instanceof HttpsURLConnection) {
            HttpsURLConnection conn = (HttpsURLConnection) connection;
            conn.setSSLSocketFactory(getSslSocketFactory());
        }

        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
//        HttpUtils.addBasicAuthToConnection(integratedUser, integratedPwd, connection);

        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        connection.setDoInput(true);
        connection.setDoOutput(true);

        String requestContent = "{'return_uri':'http://localhost:8008/idm-app', 'support_error_callback':'true'}";
        PrintWriter out = new PrintWriter(connection.getOutputStream());
        out.write(requestContent);
        out.flush();
        out.close();

        StringBuilder errBuffer = new StringBuilder();
        BufferedReader errorReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String errorLine;
        while ((errorLine = errorReader.readLine()) != null)
            errBuffer.append(errorLine);
        System.out.println(errBuffer);

        connection.disconnect();
    }
}
